package com.example.app.controller;

import com.example.app.config.LoginUser;
import com.example.app.entity.User;
import com.example.app.service.UserService;
import com.example.app.util.JwtUtil;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.crypto.SecretKey;
import java.util.*;

/**
 * Minimal auth controller (skeleton). Implement real password hashing and JWT in production.
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private JwtUtil jwtUtil;

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User reqUser) {
        try {
            String username = reqUser.getUsername();
            String password = reqUser.getPassword();
            String nickname = reqUser.getNickname();

            // 检查参数
            if (reqUser == null || password == null || username.isEmpty() || password.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("error", "Username and password are required");
                return ResponseEntity.badRequest().body(response);
            }

            // 检查用户名是否已存在
            if (userService.findByUsername(username) != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("error", "Username already exists");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建新用户
            User user = new User();
            user.setUsername(username);
            user.setPassword(passwordEncoder.encode(password)); // 密码加密
            user.setNickname(nickname != null && !nickname.isEmpty() ? nickname : username);

            User savedUser = userService.save(user);

            // 生成JWT token
            String token = jwtUtil.generateToken(savedUser.getUsername());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "User registered successfully");
            response.put("token", token);
            response.put("user", Map.of(
                    "id", savedUser.getId(),
                    "username", savedUser.getUsername(),
                    "nickname", savedUser.getNickname()
            ));

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> response = new HashMap<>();
            response.put("error", "Registration failed: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody User reqUser) {
        try {
            String username = reqUser.getUsername();
            String password = reqUser.getPassword();

            // 检查参数
            if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("error", "Username and password are required");
                return ResponseEntity.badRequest().body(response);
            }

            // 查找用户
            User user = userService.findByUsername(username);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("error", "Invalid credentials");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证密码
            if (!passwordEncoder.matches(password, user.getPassword())) {
                Map<String, Object> response = new HashMap<>();
                response.put("error", "Invalid credentials");
                return ResponseEntity.badRequest().body(response);
            }

            // 生成JWT token
            String token = jwtUtil.generateToken(user.getUsername());
            String refreshToken = jwtUtil.generateRefreshToken(user.getUsername());

            Map<String, Object> response = new HashMap<>();
            response.put("data", Map.of(
                    "token", token,
                    "refreshToken", refreshToken,
                    "user", Map.of(
                            "id", user.getId(),
                            "username", user.getUsername(),
                            "nickname", user.getNickname()
                    )
            ));

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("error", "Login failed: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/getInfo")
    public ResponseEntity<Map<String, Object>> login() {
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userService.findByUserId(principal.getUserId());
        Map<String, Object> response = new HashMap<>();
        response.put("data", Map.of(
                "roles", new ArrayList<>(),
                "user", Map.of(
                        "id", user.getId(),
                        "username", user.getUsername(),
                        "nickname", user.getNickname()
                )
        ));
        return ResponseEntity.ok(response);
    }

    public static void main(String[] args) {
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);
        System.out.println("密钥字节数组: " + Arrays.toString(secretKey.getEncoded()));
        System.out.println("Base64编码: " + Base64.getEncoder().encodeToString(secretKey.getEncoded()));
    }
}
